package com.cbs.android.component.network;


import com.cbs.android.component.log.L;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * Created by broche on 10/16/15.
 */
public abstract class SimpleResponseHandler<T> implements ResponseHandler {
    private static final String TAG = SimpleResponseHandler.class.getName();

    public abstract void onSuccess(T entity);

    public abstract void onFailure(int code, String message);

    public void onTimeout(Request request, SocketTimeoutException exception) {
    }

    public void onUnknownHost(Request request, UnknownHostException exception) {
    }

    public void onConnectException(Request request, ConnectException exception) {
    }

    public void onOtherException(Request request, Exception exception) {
    }

    public void onResponse(Response response) {
        if (response.isSuccessful()) {
            onSuccess(((T) response.getResult()));
        } else {
            onFailure(response.getCode(), response.getResult().toString());
        }
    }

    @Override
    public void onException(Request request, Exception e) {
        L.e(TAG, "", e);
        if (SocketTimeoutException.class.isAssignableFrom(e.getClass())) {
            onTimeout(request, ((SocketTimeoutException) e));
        } else if (UnknownHostException.class.isAssignableFrom(e.getClass())) {
            onUnknownHost(request, ((UnknownHostException) e));
        } else if (ConnectException.class.isAssignableFrom(e.getClass())) {
            onConnectException(request, ((ConnectException) e));
        } else {
            onOtherException(request, e);
        }
    }
}
